package com.ice.remoting.listener;

import cn.hutool.core.util.ObjectUtil;
import com.ice.remoting.NettyServerConfig;
import com.ice.remoting.netty.DeviceManager;
import com.ice.remoting.utils.SpringContextUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

@Slf4j
public class DefaultChannelEventListener implements ChannelEventListener {

    private DeviceManager deviceManager;

    private NettyServerConfig nettyServerConfig;

    private ApplicationContext applicationContext = SpringContextUtil.applicationContext;

    public DefaultChannelEventListener(NettyServerConfig nettyServerConfig) {
        this.nettyServerConfig = nettyServerConfig;
    }

    @Override
    public void onChannelConnect(String remoteAddr, Channel channel) {
        if (deviceManager != null) {
            deviceManager.putDeviceLive(remoteAddr, nettyServerConfig.getChannelExpireTime() , channel);
        }
    }

    @Override
    public void onChannelClose(String remoteAddr, Channel channel) {
        if (deviceManager != null) {
            deviceManager.remove(channel);
            ChannelDisConnectionEvent channelDisConnectionEvent = new ChannelDisConnectionEvent(this, channel);
            if (ObjectUtil.isNotEmpty(applicationContext)) {
                applicationContext.publishEvent(channelDisConnectionEvent);
            }
        }
    }

    @Override
    public void onChannelException(String remoteAddr, Channel channel) {
//        if (deviceManager != null) {
//            deviceManager.remove(channel);
//            ChannelDisConnectionEvent channelDisConnectionEvent = new ChannelDisConnectionEvent(this, channel);
//            if (ObjectUtil.isNotEmpty(applicationContext)) {
//                applicationContext.publishEvent(channelDisConnectionEvent);
//            }
//        }
    }

    @Override
    public void onChannelIdle(String remoteAddr, Channel channel) {
        if (deviceManager != null) {
            deviceManager.remove(channel);
            ChannelDisConnectionEvent channelDisConnectionEvent = new ChannelDisConnectionEvent(this, channel);
            if (ObjectUtil.isNotEmpty(applicationContext)) {
                applicationContext.publishEvent(channelDisConnectionEvent);
            }
        }
    }

    @Override
    public void onChannelActive(String remoteAddr, Channel channel) {

    }

    @Override
    public void setManagerRouter(DeviceManager deviceManager) {
        this.deviceManager = deviceManager;
    }
}
